#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT            8080
#define BUFFER_LEN      4096

int main() {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in serv_addr;
    
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);

    if (-1 == connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
        std::cout << "Connect failed!" << std::endl;
        return -1;
    }

    for (int i = 0; i < 10; ++i) {
        char buffer[BUFFER_LEN] = {0};
        if (recv(sockfd, buffer, sizeof(buffer), 0) <= 0) {
            break;
        }
        std::cout << "Message from server: " << buffer << std::endl;

        const char *msg = "Hello, Client!";
        if (send(sockfd, msg, strlen(msg), 0) == -1) {
            std::cout << "send buffer return " << errno << ", " << strerror(errno) << std::endl;
            break;
        }
        sleep(1);
    }

    close(sockfd);
    return 0;
}